<?php
namespace app\attendance\controller;

use app\api\Controller;
use think\Db;
use app\api\Base;
use think\Exception;
/**
 * 公共上传控制器类
 * 继承了图片，文件上传方法 包括一些业务逻辑的处理
 * 图片上传本地，七牛云，execl上传试题等
 */
class Upload extends Base
{
	/**
     * 文件上传本地
     */
    public function upload()
    {
    	$msg = ['code'=>400, 'msg'=>'上传失败', 'data'=>[]];
        $file = $this->request->file('file');
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path);
        if (!$info) {
        	$msg['msg'] = $file->getError();
            return json_encode($msg);
        }
        $data = $this->request->root() . '/tmp/uploads/' . $info->getSaveName();
        $insert = [
            'cate'     => 3,
            'name'     => $data,
            'original' => $info->getInfo('name'),
            'domain'   => '',
            'type'     => $info->getInfo('type'),
            'size'     => $info->getInfo('size'),
            'mtime'    => time(),
        ];
        Db::name('File')->insert($insert);

        $msg['code'] = 200;
        $msg['msg']= '上传成功';
        $msg['data'] = $data;

        return json_encode($msg);
    }

    /**
     * 文件上传到七牛云
     */
    public function qiniuUploadfile()
    {
    	$msg = ['code'=>400, 'msg'=>'上传到七牛云失败', 'data'=>[]];
        $result = \Qiniu::instance()->upload();//七牛上传
        $url=config("qiniu.QINIU_DOMAIN").$result[0]['key'];
        $insert = [
            'cate'     => 3,
            'name'     => $url,
            'original' => $result[0]['name'],
            'domain'   => config("qiniu.QINIU_DOMAIN"),
            'type'     => $result[0]['type'],
            'size'     => $result[0]['size'],
            'mtime'    => time(),
        ];
   		$msg['code'] = 200;
   		$msg['msg'] = "上传成功";
   		$msg['data'] = ['url'=>$url, 'name'=>$result[0]['name']]; 
       return json_encode($msg);
    }
}